import React, { useEffect, useState } from "react";
import { Button, Table, Modal, Tree } from "antd";
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
import axios from "axios";
const { confirm } = Modal;

const RoleList = () => {
  const [dataSource, setDataSource] = useState([]);
  const [rightList, setRightList] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentRights, setCurrentRights] = useState([]);
  const [currentId, setCurrentId] = useState(0);

  const currentRightsHandle = (item) => {
    setIsModalOpen(true);
    console.log(item);
    setCurrentRights(item.rights);
    setCurrentId(item.id);
  };

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
    },
    {
      title: "角色名称",
      dataIndex: "roleName",
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <div>
            <Button
              shape="circle"
              type="primary"
              icon={<DeleteOutlined />}
              onClick={() => confirmHandle(item)}
            ></Button>
            <Button
              shape="circle"
              type="primary"
              icon={<EditOutlined />}
              onClick={() => currentRightsHandle(item)}
            ></Button>
          </div>
        );
      },
    },
  ];

  const deleteHandle = (item) => {
    setDataSource(dataSource.filter((data) => data.id !== item.id));
  };

  const confirmHandle = (item) => {
    confirm({
      title: "確定要刪除嗎?",
      icon: <DeleteOutlined />,
      onOk() {
        deleteHandle(item);
      },
      onCancel() {
        console.log("111");
      },
    });
  };
  useEffect(() => {
    const apiUrl ="/roles";
    fetch(apiUrl)
      .then((res) => res.json())
      .then((res) => {
        setDataSource(res);
      });
  }, []);
  useEffect(() => {
    const apiUrl = "/rights";
    fetch(apiUrl)
      .then((res) => res.json())
      .then((res) => {
        setRightList(res);
      });
  }, []);

  function handleOk() {
    setIsModalOpen(false);
    setDataSource(dataSource.map((item) => {
      if (item.id === currentId) {
        return {
          ...item,
          rights: currentRights
        }
      }
      return item;
    }))

    axios.patch(`/roles/${currentId}`, {
      rights: currentRights
    })
    }

  function handleCancel() {
    setIsModalOpen(false);
  }

  const onCheck = (checkedKeys) => {
    setCurrentRights(checkedKeys);
  };
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={(row) => row.id}
      ></Table>
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Tree
          checkable
          checkStrictly
          treeData={rightList}
          checkedKeys={currentRights}
          onCheck={onCheck}
        ></Tree>
      </Modal>
    </div>
  );
};

export default RoleList;
